<?php
namespace app\api\controller\v1;

use \app\common\controller\ApiCommon;
use \app\common\model\Building;

class Buildings extends ApiCommon
{
    protected $modelName = 'Building';

    /**
     * 读取教学楼绑定情况
     *
     * @return void
     */
    public function index()
    {
        $this->checkPermission(0); //此接口只有超级管理员才有权限调用
        $all = Building::all()->toArray();
        $table=[];
        foreach($all as $v){
            $table[$v['name']]=$v['key'];
        }

        $buildings = db('room')->whereExp('building', 'is not null')->distinct(true)->column('building');
        $ret = [];
        foreach ($buildings as $v) {
            if (isset($table[$v])) {
                $ret[] = ['name' => $v, 'key' => md5($table[$v])];
            } else {
                $ret[] = ['name' => $v, 'key' => ""];
            }
        }

        return json_response($ret, STATUS_OK);
    }

    /**
     * 删除指定的教学楼的绑定
     *
     * @param [type] $id
     * @return void
     */
    public function delete($id){
        $this->checkPermission(0);
        return parent::_delete($id);
    }

    /**
     * 删除多个教学楼的绑定
     */
    public function deletes($ids){
        $this->checkPermission(0);
        return parent::_deletes($ids);
    }

    /**
     * 绑定签到Key
     *
     * @return void
     */
    public function registerKey()
    {
        $this->checkPermission(0); //此接口只有超级管理员才有权限调用
        $request = $this->request;
        $name = $request->param('name');
        if ($name === null) {
            return json_response([], STATUS_INVALD_PARAM, "必须填写name参数");
        }

        $keyY = $request->param('key');
        if ($keyY === null) {
            return json_response([], STATUS_INVALD_PARAM, "必须填写key参数");
        }

        $key = Building::decodeKey($keyY, model('SystemConfig')->getValueInt('BKeyExpire'));

        if ($key !== false) {
            try {
                $building = Building::get($name);
                if ($building) {
                    $building->key = $key;
                    $building->save();
                } else {
                    Building::create(['name' => $name, 'key' => $key]);
                }
                return json_response([md5($key)], STATUS_OK);
            } catch (\Exception $err) {
                return json_response([], STATUS_FAIL, "保存key时出错" . $err);
            }
        } else {
            return json_response([], STATUS_FAIL);
        }
    }

    /**
     * 解除绑定签到地点
     *
     * @return void
     */
    public function unregisterKey(){
        $this->checkPermission(0); //此接口只有超级管理员才有权限调用
        $request = $this->request;
        $name = $request->param('name');
        if ($name === null) {
            return json_response([], STATUS_INVALD_PARAM, "必须填写name参数");
        }
        Building::where('name',$name)->delete();
        return json_response([]);
    }
}
